package com.dgut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dgut.constant.AccountNotFoundException;
import com.dgut.constant.MessageConstant;
import com.dgut.dto.RegisterDTO;
import com.dgut.dto.UserDTO;
import com.dgut.entity.Employee;
import com.dgut.entity.User;
import com.dgut.exception.PasswordErrorException;
import com.dgut.mapper.EmployeeMapper;
import com.dgut.mapper.UserMapper;
import com.dgut.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Employee login(UserDTO userDTO) {
        //查找用户
        String account = userDTO.getAccount();
        String password = userDTO.getPassword();

        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        Employee employee = employeeMapper.selectOne(queryWrapper);

        if (employee == null) {
            //抛出异常
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对

        if (!employee.getPassword().equals(password)) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //返回用户信息
        return employee;
    }

    /**
     * 用户注册
     *
     * @param registerDTO
     */
    @Override
    public void register(RegisterDTO registerDTO) {
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        userMapper.insert(user);
    }

    /**
     * 获取注册数据
     *
     * @return
     */
    @Override
    public List<User> getRegisterData() {
        return userMapper.selectList(null);
    }
}
